import jieba,random,json

DOT_LIST=list('”“。,；‘’.!?？！<>:：()@ ')

class Converter:
    class ConverterError(Exception):
        def __init__(self,reason):
            self.reason=reason
        def __str__(self):
            return self.reason
    def __init__(self,max_size):
        '''
        生成一个词语与向量的转换器
        '''
        self.MAX_SIZE=max_size
        self.word_l=[]
        self.value_l=[] #词语与向量的列表
    def w2v(self,word):
        '将词语转换为值'
        if word in self.word_l:
            return self.value_l[self.word_l.index(word)]
        else:
            self.word_l.append(word)
            r=random.randint(1,self.MAX_SIZE)
            self.value_l.append(r)
            return r
    def v2w(self,value):
        '将一个值转换回词语'
        if value in self.value_l:
            return self.word_l[self.value_l.index(value)]
        else:
            return None
    def dumps(self):
        '''
        保存向量数据
        '''
        return json.dumps([self.word_l,self.value_l])
    def loads(self,text):
        '''
        加载向量数据
        '''
        d=json.loads(text)
        if len(d[0])!=len(d[1]):
            raise self.ConverterError('数组长度不等')
        else:
            self.word_l=d[0]
            self.value_l=d[1]
    def s2v(self,sentense):
        '''
        句到向量的转换
        '''
        s_l=list(jieba.cut(sentense))
        #记得去掉标点符号
        for i in s_l:
            if i in DOT_LIST:
                del s_l[s_l.index(i)]
        v_l=[]
        for j in s_l:
            v_l.append(self.w2v(j))
        return v_l
        